package com.tm;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.StringTokenizer;

import com.tm.pojo.Instrument;

public class InstumentsTextFileLoader {
	String filename;
	
	public InstumentsTextFileLoader(String filename) {
		this.filename = filename;
	}
	
	public Iterator<Instrument> iterator() throws FileNotFoundException {
		InstrumentsTextFileIterator iterator = new InstrumentsTextFileIterator(filename);
		return iterator;
	}
	
	public class InstrumentsTextFileIterator implements Iterator<Instrument> {
		private FileInputStream file;
		private Scanner scanner;
		
		public InstrumentsTextFileIterator(String filename) throws FileNotFoundException {
			file = new FileInputStream(filename);
			scanner = new Scanner(file);
		}
		
		@Override
		public boolean hasNext() {
			if (!scanner.hasNextLine()) {
				scanner.close();
				return false;
			} else {
				return true;
			}
		}

		@Override
		public Instrument next() {
			Instrument i = new Instrument();
			String line = scanner.nextLine();
			line = line.trim();
			if (line.length()>0) {
				StringTokenizer tokenizer = new StringTokenizer(line, "|");
				if(tokenizer.countTokens() != 8) {
					return null;
				}
				i.setStrTerm(tokenizer.nextToken());
				i.setName(tokenizer.nextToken());
				i.setType(tokenizer.nextToken());
				i.setDefinition(tokenizer.nextToken());
				i.setBloombergId(tokenizer.nextToken());
				i.setCurrency(tokenizer.nextToken());
				i.setDaycountConvention(tokenizer.nextToken());
				i.setCompoundingFrequency(tokenizer.nextToken());
			} else {
				return null;
			}
			
			return i;
		}

		@Override
		public void remove(){
			//do nothing
		}
		
	}
	
}
